/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 *
 */
import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';


import { runHvigorFailAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
};

const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  const entryModule = project.getModule('entry');
  const entryModuleJson5 = path.resolve(entryModule.moduleRootPath(), 'src', 'main', 'module.json5');
  const entryModuleJson5Bak = path.resolve(entryModule.moduleRootPath(), 'src', 'main', 'module.json.bak');
  fse.renameSync(entryModuleJson5, entryModuleJson5Bak);
  const commands: string[] = '--mode project -p product=default assembleHap --analyze=normal --parallel --incremental --no-daemon '.split(' ');
  const result = await runHvigorFailAsync(projectRootPath, commands);
  record.addStep('1. 修改module.json5为module.json5.bak，构建entry', result);
  expect(result.stderr).toContain('00304064');
  fse.renameSync(entryModuleJson5Bak, entryModuleJson5);


  const appJson5 = path.resolve(projectRootPath, 'AppScope', 'app.json5');
  const appJson5Bak = path.resolve(projectRootPath, 'AppScope', 'app.json5.bak');
  fse.renameSync(appJson5, appJson5Bak);
  const result1 = await runHvigorFailAsync(projectRootPath, commands);
  record.addStep('2. 修改app.json5为app.json5.bak，构建entry', result1);
  expect(result1.stderr).toContain('00304066');
  fse.renameSync(appJson5Bak, appJson5);
};

TestCaseBuilder.builder()
  .caseName('BASE_FILE_VALIDATE')
  .description('看护app.json5、module.json5不存在时的报错')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L0).build())
  .testFun(testfun)
  .load();
